<?php
namespace Admin\Domain\Iadminosoauth;

use Portal\Domain\Admin as AdminDomain;

/**
 * OAuth领域层
 * @author dogstar 20201220
 *
 */
class OAuth {
    
    /**
     * OAuth登录
     * @param string $password 账号
     * @param string $username 密码
     * @param string &$error 错误提示
     * @return boolean 是否登录成功
     */
    public function login($username, $password, &$error = null) {
        $isLogin = false;
        if ($password && $username) {
            // https://oauth2-client.thephpleague.com/usage/
            // curl -u iadminos:123456 http://demo.iadminos.com/oauth/token.php -d 'grant_type=password&username=admin&password=123456'
            $oauthConfig = \PhalApi\DI()->config->get('iadminos_oauth.oauth');
            $provider = new \League\OAuth2\Client\Provider\GenericProvider($oauthConfig);
            
            try {
                
                // Try to get an access token using the resource owner password credentials grant.
                $accessToken = $provider->getAccessToken('password', [
                    'username' => $username,
                    'password' => $password, // sha1
                ]);
                $domain = new AdminDomain();
                $admin = $domain->getByUsername($username);
                
                // 同步到本地
                if (!$admin) {
                    $domain->createAdmin($username, $password);
                    $admin = $domain->getByUsername($username);
                }
                
                // 开启会话
                $userId = $admin['id'];
                $role = $admin['role'];
                \PhalApi\DI()->admin->login($userId, $username, $role, $accessToken);
                
                $isLogin = true;
                
            } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
                // Failed to get the access token
                // throw $e;
                $error = '认证失败，' . $e->getMessage();
                
            }
        } else {
            $error = '缺少账号或密码';
        }
        return $isLogin;
    }
}
